$(document).ready(function() {
    addClassToCurrentContent();
    noOverflow();
    activeFirstSearchForm();

    $('#button-go-home').live('click',function(){
        goToLink($(this).attr('data-url'));
    });
    $('#account-forgotten').click(function(){
        sendPassword($('.account-forgotten form.forgotten'));
    });
    $('#logout-link').click(function(){
        logout($(this).attr('href')); return false;
    });
    $('#login-submit-button').click(function(){
        login($('#login-form form').serialize());
    });
    $('#account-back-button').click(function(){
        goToLink($(this).attr('data-url'));
    });
    $('#account-insert-button').click(function(){
        goToLink($(this).attr('data-url'));
    });
    $('#search-form form').keypress(function(event){
        if(event.keyCode=='0xA' || event.keyCode=='0xD') lekoSearch($(this).serialize(), $(this));
    });
    $('#order-checkout').live('click', function(){
        goToLink($(this).attr('data-url'));
    });
    $('#order-reset').live('click', function(){
        resetOrder($(this));
    });
    $('#add-to-cart').live('click', function(){
        addProductToCart($('#articles-tables input.quantity').serialize());
    });
    $('#search-form .search-form').click(function(event){
        searchFormActive($(this), event);
    });
    $('#search-form a.button').live('click', function(){
        var form=$('#'+$(this).parent('div').parent('td').attr('id').replace('-button',''));
        var data=form.serialize();
        lekoSearch(data, form);
    });
    $('#search-form .model-search-form select').live('click', function(){
        $(this).css('color', '#000');
    });
    $('#articles-tables a.vendors').live('click', function(){
        lekoSearch('vendor='+$(this).attr('name'), false);
    });
    $('#top-menu .tcmenu td.button').click(function(){
        goToLink($(this).attr('data-url'));
    });
    $('#information-block p.information-links').click(function(){
        goToLink($(this).attr('data-url'));
    });
    $('#column-right .box-category li').click(function(){
        goToLink($(this).attr('data-url'));
    });
    $('#category-block .subcategories li').click(function(){
        goToLink($(this).attr('name'));
    });
    $('#table-product input.quantity').live('keypress', function(event){
        if(event.keyCode=='0xA' || event.keyCode=='0xD') updateCart($(this).attr('data-id'), $(this).val());
    });
    $('#table-product input[name=remove]').live('click', function(){
        removeItem($(this).val());
    });
    $('#account-order a.button-update').live('click',function(){
        updateAccountOrder($(this));
    });
    $('#articles-tables').live('keypress',function(event){
        if(event.keyCode=='0xA' || event.keyCode=='0xD') addProductToCart($('#articles-tables-form').serialize());
    });
    $(document).live('keypress',function(event){
        if(event.keyCode=='0xA' || event.keyCode=='0xD') footerPosition();
    });

	search();
	ajaxCart();
	megaMenu();
	IEFixing();
    removeAlertmessage();
    footerPosition();
});

function noOverflow(){
    var diffHeight=$(window).height()-$('#container').height()-$('#powered').height();
    if('\v'=='v') diffHeight++;
    if(diffHeight>=0) $('html').css('overflow', 'hidden');
}

function footerPosition(){
    var different=$('#content').height()-$(document).height()+170;
    console.log(different);
    if(different>0){
        different+=100;
        $('#powered').css('top',different+'px');
    }
}

function activeFirstSearchForm(){
    $('#search-form .article-search-form').addClass('active');
    $('#search-form form.active input[name=art]').focus();
}

function searchFormActive(form, event){
    $('#search-form form.active').removeClass('active');
    form.addClass('active');

    if(event.target.nodeName!='INPUT' && event.target.nodeName!='SELECT'){
        $('input:first', form).focus();
        $('select:first', form).focus();
    }
}

function goToLink(url){
    location.href=url;
}

function getURLVar(urlVarName) {
	var urlHalves = String(document.location).toLowerCase().split('?');
	var urlVarValue = '';
	
	if (urlHalves[1]) {
		var urlVars = urlHalves[1].split('&');

		for (var i = 0; i <= (urlVars.length); i++) {
			if (urlVars[i]) {
				var urlVarPair = urlVars[i].split('=');
				
				if (urlVarPair[0] && urlVarPair[0] == urlVarName.toLowerCase()) {
					urlVarValue = urlVarPair[1];
				}
			}
		}
	}
	
	return urlVarValue;
}

function lekoSearch(data, form){
    var loadingSelector='';
    if(form){
        loadingSelector='.'+form.attr('class').split(' ')[0]+' .loading';
        var searchInput=form.find('.search-input input');
        searchInput.attr('value','');
        searchInput.autofocus;
    }
    $.ajax({
        url: 'index.php?route=module/lekoService/search',
        type: 'post',
        data: data,
        dataType: 'json',
        beforeSend: function(){
            displayLoad(loadingSelector);
        },
        complete: function(){
            hideLoad(loadingSelector);
        },
        success: function(json){
            if(json.result){
                $('#search-result .text-search').css('display', 'none');
                $('#search-result .search-notice').css('display', 'none');
                $('#articles-tables').removeAttr('style');
                $('#articles-tables-form').html(json['result']);
            }else{
                $('#articles-tables').css('display', 'none');
                $('#search-result .text-search').css('display', 'none');
                if(json.error==1) $('#search-result .search-notice').css('display', 'block');
                else{
                    $('#search-result .search-notice').html(json.error);
                    $('#search-result .search-notice').css('display', 'block');
                }
            }
        }
    });
}

function addToCart(id, quantity){
    if(typeof quantity=='undefined') quantity=1;
    product=id+'='+quantity+'&success=1';
    addProductToCart(product);
}

function addProductToCart(products){
    $.ajax({
		url: 'index.php?route=checkout/cart/add',
		type: 'post',
		data: products,
		dataType: 'json',
        beforeSend: function(){
            displayLoad('#to-cart-loading');
        },
        complete: function(){
            hideLoad('#to-cart-loading');
        },
		success: function(json) {
			$('.success, .warning, .attention, .information, .error').remove();

            if(json['products']) $('#products-container').removeAttr('style');

			if (json['redirect']) {
				location = json['redirect'];
			}

            $('#notification').html('<div class="success" style="display: none;">' + json['success'] + '<img src="catalog/view/theme/default/image/close.png" alt="" class="close" /></div>');

            if(json['products']){
                $('#articles-tables').css('display', 'none');
                for(var id in json['products']){
                    var selector='#product-'+id;
                    if($(selector).length>0){
                        $(selector).remove();
                    }

                    $('#products-list').append(json['products'][id]);

                    if(json['success'].length>0){
                        $('#notification').html('<div class="success" style="display:none;">'+json['success']+'<img src="catalog/view/theme/default/image/close.png" alt="" class="close" /></div>');
                        $('.success').fadeIn('slow');
                    }
                }
            }

            updateTotals();
		}
	});
}

function updateCart(product_id, quantity){
    quantity=typeof(quantity)!='undefined' ? quantity : 1;
    selector='#product-'+product_id;

    $.ajax({
        url: 'index.php?route=checkout/cart/update',
        type: 'post',
        data: 'product_id='+product_id+'&quantity='+quantity,
        dataType: 'json',
        success: function(json) {
            $('.success, .warning, .attention, .information, .error').remove();

            if (json['redirect']) {
                location=json['redirect'];
            }

            if(quantity>0){
                $(selector).html(json['product']);
            }else{
                $(selector).remove();
            }

            updateTotals();
        }
    });
}

function removeItem(product_id){
    selector='#product-'+product_id;
    $.ajax({
        url: 'index.php?route=checkout/cart/remove',
        type: 'post',
        data: 'product_id='+product_id,
        dataType: 'json',
        success: function(json) {
            $('.success, .warning, .attention, .information, .error').remove();

            if (json['redirect']) {
                location=json['redirect'];
            }

            if(json['result']){
                $(selector).remove();
                if(!$('#products-list tr').length){
                    $('#products-container').attr('style', 'display: none;');
                }
            }

            updateTotals();
        }
    });
}

function updateAccountOrder(href){
    var url=href.attr('data-id');
    var top=(window.innerHeight-300)/2;
    var left=(window.innerWidth-500)/2;

    displayPopup(url,'remove product',500,300,top,left);
}

function resetOrder(span){
    $.ajax({
        url: 'index.php?route=checkout/cart/resetOrder',
        type: 'post',
        data: 'reset=true',
        dataType: 'json',
        success: function(json) {
            if(json.result){
                $('.success, .warning, .attention, .information, .error').remove();
                $('#products-container').remove();
                goToLink(span.attr('data-url'));
            }
        }
    });
}

function updateTotals(){
    $.ajax({
        url: 'index.php?route=checkout/cartTotal',
        type: 'post',
        data: 'update='+'1',
        dataType: 'json',
        success: function(json){
            if(json.length>=1){
                for(var i in json){
                    var selector='#'+i+'-total';
                    $(selector).html(json[i]);
                }
            }
        }
    });
}

function addToWishList(product_id) {
	$.ajax({
		url: 'index.php?route=account/wishlist/add',
		type: 'post',
		data: 'product_id=' + product_id,
		dataType: 'json',
		success: function(json) {
			$('.success, .warning, .attention, .information').remove();
						
			if (json['success']) {
				$('#notification').html('<div class="success" style="display: none;">' + json['success'] + '<img src="catalog/view/theme/default/image/close.png" alt="" class="close" /></div>');
				
				$('.success').fadeIn('slow');
				
				$('#wishlist-total').html(json['total']);
				
				$('html, body').animate({ scrollTop: 0 }, 'slow');
			}	
		}
	});
}

function addToCompare(product_id) { 
	$.ajax({
		url: 'index.php?route=product/compare/add',
		type: 'post',
		data: 'product_id=' + product_id,
		dataType: 'json',
		success: function(json) {
			$('.success, .warning, .attention, .information').remove();
						
			if (json['success']) {
				$('#notification').html('<div class="success" style="display: none;">' + json['success'] + '<img src="catalog/view/theme/default/image/close.png" alt="" class="close" /></div>');
				
				$('.success').fadeIn('slow');
				
				$('#compare-total').html(json['total']);
				
				$('html, body').animate({ scrollTop: 0 }, 'slow'); 
			}	
		}
	});
}

function login(data){
    $.ajax({
        url: 'index.php?route=account/login',
        type: 'post',
        data: data,
        dataType: 'json',
        success: function(json){
            if(json.redirectUrl) goToLink(json.redirectUrl);
            $('#login-form .error').html(json.error);
        }
    });
}

function logout(link){
    $.ajax({
        url: link,
        type: 'get',
        data: 'logout=1',
        dataType: 'json',
        success: function(json){
            if(json.redirectUrl) goToLink(json.redirectUrl);
        }
    });
}

function sendPassword(form){
    loadingSelector='.'+form.attr('class').split(' ')[0]+' .loading';
    console.log(loadingSelector);
    $.ajax({
        url: form.attr('action'),
        type: 'post',
        data: form.serialize(),
        dataType: 'json',
        beforeSend: function(){
            displayLoad(loadingSelector);
        },
        complete: function(){
            hideLoad(loadingSelector);
        },
        success: function(json){
            if(json.error){
                $('.account-forgotten span.error').html(json.error);
            }
            if(json.user_message){
                $('#user-message').html(json.user_message);
                var button=$('.'+$(form).attr('class')+' input.button');
                button.attr('id','button-go-home');
                button.attr('data-url',json.redirect_url);
            }
        }
    });
}

function addClassToCurrentContent(){
    var url=window.location.toString();
    if(url.indexOf('route=')+1){
        var style=url.split('route=')[1].replace('/', '-');
        $('div.content').attr('class', 'content '+style);
    }
}

function IEFixing(){
    if ($.browser.msie){
        if ($.browser.version <= 6) {
            $('#column-left + #column-right + #content, #column-left + #content').css('margin-left', '195px');
            $('#column-right + #content').css('margin-right', '195px');
            $('.box-category ul li a.active + ul').css('display', 'block');
        }

        if ($.browser.version <= 7) {
            $('#menu > ul > li').bind('mouseover', function() {
                $(this).addClass('active');
            });

            $('#menu > ul > li').bind('mouseout', function() {
                $(this).removeClass('active');
            });
        }
    }
}

function removeAlertmessage(){
    $('.success img, .warning img, .attention img, .information img').live('click', function() {
        $(this).parent().fadeOut('slow', function() {
            $(this).remove();
        });
    });
}

function megaMenu(){
    $('#menu ul > li > a + div').each(function(index, element) {
        // IE6 & IE7 Fixes
        if ($.browser.msie && ($.browser.version == 7 || $.browser.version == 6)) {
            var category = $(element).find('a');
            var columns = $(element).find('ul').length;

            $(element).css('width', (columns * 143) + 'px');
            $(element).find('ul').css('float', 'left');
        }

        var menu = $('#menu').offset();
        var dropdown = $(this).parent().offset();

        i = (dropdown.left + $(this).outerWidth()) - (menu.left + $('#menu').outerWidth());

        if (i > 0) {
            $(this).css('margin-left', '-' + (i + 5) + 'px');
        }
    });
}

function ajaxCart(){
    $('#cart > .heading a').live('click', function() {
        $('#cart').addClass('active');
        $('#cart').load('index.php?route=module/cart #cart > *');
        $('#cart').live('mouseleave', function() {
            $(this).removeClass('active');
        });
    });
}

function search(){
    $('.button-search').bind('click', function() {
        url = $('base').attr('href') + 'index.php?route=product/search';

        var filter_name = $('input[name=\'filter_name\']').attr('value');

        if (filter_name) {
            url += '&filter_name=' + encodeURIComponent(filter_name);
        }

        location = url;
    });

    $('#header input[name=\'filter_name\']').bind('keydown', function(e) {
        if (e.keyCode == 13) {
            url = $('base').attr('href') + 'index.php?route=product/search';

            var filter_name = $('input[name=\'filter_name\']').attr('value');

            if (filter_name) {
                url += '&filter_name=' + encodeURIComponent(filter_name);
            }

            location = url;
        }
    });
}

function displayLoad(selector){
    $(selector).css('display', 'block');
}

function hideLoad(selector){
    $(selector).css('display', 'none');
}

function displayPopup(url,name,width,height,top,left){
    window.open(url,name,'width='+width+',height='+height+',status=no,resizable=yes,top='+top+',left='+left);
}